import 'dart:developer';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_controller.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_page_counter.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/engagement/engagement_model.dart';
import 'package:pornhub_app/utils/logger.dart';

class EngagementSearchResultPageController extends BaseRefreshController
    with BaseRefreshPageCounter, GetSingleTickerProviderStateMixin {
  TextEditingController searchTextController = TextEditingController();
  late final TabController tabController;
  final getArguments = Get.arguments;

  String pageType = '';
  var searchArgument = ''.obs;
  var hotTagId = 0.obs;

  final List<Tab> tabs = const [
    Tab(text: '嫩模'),
    Tab(text: '楼凤'),
  ];

  int currentTabIndex = 0;
  RxList<EngagementModel> youngModels = <EngagementModel>[].obs;
  RxList<EngagementModel> louFengs = <EngagementModel>[].obs;

  int pageIndexYoungModels = 1;
  int pageIndexLouFengs = 1;

  @override
  void onInit() {
    super.onInit();
    initData();
  }

  void initData() {
    tabController = TabController(length: tabs.length, vsync: this);
    pageType = getArguments["searchType"];
    searchArgument.value = getArguments['searchArguments'];
    if (pageType == 'hotTag') {
      hotTagId.value = getArguments['searchHotTagId'];
    }
    searchTextController.text = searchArgument.value;
    loadHttpList(isRefresh: true);
  }

  @override
  Future<IndicatorResult> onRefresh() async {
    return await loadHttpList(isRefresh: true);
  }

  @override
  Future<IndicatorResult> onLoad() async {
    return await loadHttpList(isRefresh: false);
  }

  Future<IndicatorResult> loadHttpList({required bool isRefresh}) async {
    try {
      if (isRefresh) {
        resetPageIndex();
      } else {
        incrementPageIndex();
      }
      currentTabIndex = tabController.index;
      final response = await fetchEngagementList();
      if (response != null) {
        updateModels(response, isRefresh);
        return IndicatorResult.success;
      }
      return IndicatorResult.noMore;
    } catch (e) {
      logger.e("Error fetching data: $e");
      return IndicatorResult.fail;
    }
  }

  void resetPageIndex() {
    if (currentTabIndex == 0) {
      pageIndexYoungModels = 1;
    } else {
      pageIndexLouFengs = 1;
    }
  }

  void incrementPageIndex() {
    if (currentTabIndex == 0) {
      pageIndexYoungModels++;
    } else {
      pageIndexLouFengs++;
    }
  }

  Future<List<EngagementModel>?> fetchEngagementList() async {
    final res = await httpInstance.get<EngagementModel>(
      url: 'meet/user/list',
      queryMap: {
        'serviceTag': searchTextController.text,
        'meetType': currentTabIndex + 1,
        'classifyId': 0,
        'page': currentTabIndex == 0 ? pageIndexYoungModels : pageIndexLouFengs,
        'pageSize': 20,
      },
      complete: EngagementModel.fromJson,
    );
    if (res is List<EngagementModel>) {
      return res;
    }
    return null;
  }

  void updateModels(List<EngagementModel> response, bool isRefresh) {
    if (isRefresh) {
      if (currentTabIndex == 0) {
        youngModels.assignAll(response);
      } else {
        louFengs.assignAll(response);
      }
    } else {
      if (currentTabIndex == 0) {
        youngModels.addAll(response);
      } else {
        louFengs.addAll(response);
      }
    }
  }
}
